package com.nineclock.message.service.impl;

import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.jg.JPushManager;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    JPushManager pushManager;

    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
        //1. 存到到mongodb
        mongoTemplate.save(message);
        //2. 推送给管理员
        pushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), null);
        return null;
    }

    /**
     * 查询mongodb 存储的数据
     * @param messageDTO
     * @return
     */
    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO messageDTO) {

        if(messageDTO == null){
            return new ArrayList<>();
        }

        Query query = new Query();
        if (messageDTO.getId() != null){ // _id = 1
            query.addCriteria(Criteria.where("_id").is(messageDTO.getId()));
        }

        if(messageDTO.getUserId() != null){
            query.addCriteria(Criteria.where("applyUserId").is(messageDTO.getUserId()));
        }

        if(messageDTO.getType() != null){
            query.addCriteria(Criteria.where("messageType").is(messageDTO.getType()));
        }


        if(messageDTO.getTargetId() != null){
            query.addCriteria(Criteria.where("approveUserId").is(messageDTO.getTargetId()));
        }
        //排序, 根据审核状态升序排序（必须排序，否则会不显示）
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));

        /**
         * 参数1 ： 查询的条件
         * 参数2： 查询出来的数据，封装成 NcMessage对象
         * 返回： 消息列表
         */
        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);



        return messageList;
    }

    @Override
    public void updateMessageWithApproved(String notifyMsgId) {
        //配置条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(notifyMsgId));
        //要更新的字段
        Update update = new Update();
        update.set("useStatus",1);
        update.set("approveStatue",1);


        mongoTemplate.updateFirst(query, update, NcMessage.class);
    }
}
